package server

import (
	"sync/atomic"
	"gitee.com/thomasgw/gms/common"
	"strconv"
	"time"
	"fmt"
)

type Server struct {
	counter int32
	sendCh  chan interface{}
}

func NewServer(ch chan interface{}) *Server{
	return &Server{
		counter: int32(0),
		sendCh:  ch,
	}
}

func (srv *Server) AtomicAd() {
	atomic.AddInt32(&srv.counter, 1)
}

func (srv *Server) Start() {
	go func() {
		for {
			time.Sleep(200 * time.Millisecond)
			srv.Emit()
		}
	}()
}

func (srv *Server) Emit() {
	srvEvent := common.ServerEvent{
		EType:   common.EVENT_TYPE,
		Payload: []byte(strconv.Itoa(int(srv.counter))),
		Timestamp: strconv.Itoa(int(time.Now().UnixNano())),
	}
	srv.AtomicAd()
	srv.sendCh <- srvEvent
	fmt.Println("[SERVER] Emit an event, with counter: ", string(srvEvent.Payload))
}

